package log

import (
	rotatelog "github.com/lestrrat-go/file-rotatelogs"
	"github.com/rifflock/lfshook"
	"github.com/sirupsen/logrus"
	"os"
	"time"
)

var Logger = logrus.New()

func InitLog() {
	var timeStr = time.Now().Format("2006-01-02")
	filePath := "log/" + timeStr + "_log.log"
	lineName := "latest_log.log"
	scr, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE, 0755)
	if err != nil {
		Logger.Error(err)
	}

	logger := logrus.New()

	logger.Out = scr

	logger.SetLevel(logrus.DebugLevel)
	logWriter, _ := rotatelog.New(
		filePath,                                 //文件名
		rotatelog.WithMaxAge(7*24*time.Hour),     //保存时间
		rotatelog.WithRotationTime(24*time.Hour), //分割时间
		rotatelog.WithLinkName(lineName),         //软连接
	)
	writerMap := lfshook.WriterMap{
		logrus.InfoLevel:  logWriter,
		logrus.FatalLevel: logWriter,
		logrus.DebugLevel: logWriter,
		logrus.WarnLevel:  logWriter,
		logrus.ErrorLevel: logWriter,
		logrus.PanicLevel: logWriter,
	}

	Hook := lfshook.NewHook(writerMap, &logrus.TextFormatter{
		TimestampFormat: "2006-01-02 15:04:05",
	})

	logger.AddHook(Hook)
	Logger = logger
	//示例
	//Logger.Info("这是一条日志")
	//Logger.Error("这是一条错误")
}
